package com.core.config;

import com.core.toolkit.jwt.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 禁用 CSRF 和 session 管理
                .csrf(CsrfConfigurer::disable)
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )

                // 授权规则配置
                .authorizeHttpRequests(auth -> auth
                        // 允许匿名访问的端点
                        .requestMatchers(
                                "/user/login","/user/register", // 登录和注册接口
                                "/test/**",                    // 测试接口
                                "/swagger-resources/**", "/doc.html", "/webjars/**",
                                "/v2/**", "/swagger-ui.html/**","/swagger-ui/**",                        // Swagger 接口文档
                                "/v3/api-docs/**",             // API 文档
                                "/public/**"                   // 所有公开资源
                        ).permitAll()

                        // 需要认证的端点
                        .anyRequest().authenticated()
                )

                // 添加 JWT 过滤器
                .addFilterBefore(
                        jwtAuthenticationFilter,
                        UsernamePasswordAuthenticationFilter.class
                );

        return http.build();
    }
}